package cn.edu.hust.sse.software7.class3.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.hust.sse.software7.class3.entities.EBCategory;
import cn.edu.hust.sse.software7.class3.service.EBCategoryService;
import cn.edu.hust.sse.software7.class3.serviceImpl.EBCategoryServiceImpl;

public class CategoryServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	EBCategoryService ebcs = new EBCategoryServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");
		if(method.equals("deletecategory")){
			HttpSession session = req.getSession();
			String a2Del = req.getParameter("category2Delete");
			Long categoryId = new Long(a2Del);
			EBCategoryService ebcs = new EBCategoryServiceImpl();
			List<EBCategory> subCat = ebcs.getCategoriesByPid(categoryId);
			if(null == subCat || subCat.isEmpty()) {			
				ebcs.deleteCategoryById(categoryId);
			}else{			
			}
			
			List<EBCategory> categories = ebcs.getCategories();
			session.setAttribute("categories", categories);
			resp.sendRedirect("admin/productManage/watchCategories.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String method = req.getParameter("method");
		if(method.equals("addcategory")){
			HttpSession session = req.getSession();			
			String categoryName = req.getParameter("categoryName");
			String categoryDesc = req.getParameter("categoryDesc");
			EBCategory category2Add = new EBCategory(categoryName, categoryDesc);
			
			if (!ebcs.isExistCategory(category2Add)) {
				ebcs.addCategory(category2Add);
				session.setAttribute("AddCategoryResult", "添加目录成功！");
				resp.sendRedirect("admin/productManage/addCategory.jsp");
			} else {
				session.setAttribute("AddCategoryResult", "该目录已经存在！");
				resp.sendRedirect("admin/productManage/addCategory.jsp");
			}
		}
		
	}

}
